package com.profgj.profgj.controller;

import com.profgj.profgj.entity.ProjectImportantDocument;
import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.service.ProjectImportantDocumentService;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.validater.ProjectImportantDocumentVoValidator;
import com.profgj.profgj.vo.EmptyObject;
import com.profgj.profgj.vo.ProjectImportantDocumentVo;
import com.profgj.profgj.vo.ResultMsg;
import com.profgj.profgj.vo.ReturnResult;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
/**
 * (项目要件)控制层
 *
 * @author 杨帅
 * @since 2021-06-22 11:09:35
 */

/**
 * JSON格式返回
 */
@RestController
/**
 * 请求基路径
 */
@RequestMapping("/reqment")
@Api(tags = {"项目要件"},description = "项目要件")
public class RequirementsController {

    /**
     * 项目要件服务对象
     */
    @Resource
    private ProjectImportantDocumentService projectImportantDocumentService;

    /**
     * 返回空对象的替代品
     */
    private EmptyObject emptyObject = new EmptyObject();


    /**
     * 初始化设置校验器
     * @param binder    校验器绑定对象
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 绑定企业校验器
        binder.setValidator(new ProjectImportantDocumentVoValidator());

    }


    /**
     * 通过id查询 项目要件
     * @param id    项目要件id
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @GetMapping("/requirements/{id}")
    @ApiOperation(value = "通过id查询 项目要件",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "项目要件id", required = true, dataType = "Long", paramType = "Long", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> requirementsQueryByIdMethod(@PathVariable("id") Long id, @ApiIgnore HttpSession session){

        // id参数校验
        if (!EmptyUtils.isLongEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        ProjectImportantDocumentVo projectImportantDocumentVo = null;
        if (role_id != 1) {
            //不是管理员情况下
            // id查询企业数据库
            projectImportantDocumentVo = projectImportantDocumentService.queryByIdAndUserId(id,user_id);
        } else {
            //是管理员情况下
            // id查询项目要件
            projectImportantDocumentVo = projectImportantDocumentService.queryById(id);
        }

        // 判断查询后的数据是否存在
        if(!EmptyUtils.isProjectImportantDocumentEmpty(projectImportantDocumentVo)) {
            return ReturnOperator.createResultMsg("", ServerStatus.PID_NOT_EXISTS, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                new ArrayList<>(), projectImportantDocumentVo, HttpStatus.OK);
    }


    /**
     * 获取项目要件列表
     * @param offset    查询起始位置
     * @param limit     查询条数
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @GetMapping("/requirements/list/{offset}/{limit}")
    @ApiOperation(value = "查询起始位置",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "offset",value = "查询起始位置", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "limit",value = "查询条数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> requirementsQueryListMethod(@PathVariable("offset") Integer offset,
                                                                  @PathVariable("limit") Integer limit,
                                                                  @ApiIgnore HttpSession session){

        // 参数校验
        if (!EmptyUtils.isIntegerEmpty(offset) && !EmptyUtils.isIntegerEmpty(limit)) {
            return ReturnOperator.createResultMsg("", ServerStatus.LIMIT_PARAM_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        List<ProjectImportantDocumentVo> projectImportantDocuments = null;
        if (role_id != 1) {
            //不是管理员情况下
            // 分页查询项目要件列表
            projectImportantDocuments = projectImportantDocumentService.queryAllByUserIdAndLimit(offset, limit, user_id);
        } else {
            //是管理员情况下
            // 分页查询项目要件列表
            projectImportantDocuments = projectImportantDocumentService.queryAllByLimit(offset, limit);
        }

        // 查询结果判断是否为空
        if (!EmptyUtils.isProjectImportantDocumentListEmpty(projectImportantDocuments)) {
            return ReturnOperator.createResultMsg("", ServerStatus.PID_NOT_EXISTS, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                projectImportantDocuments, emptyObject, HttpStatus.OK);
    }


    /**
     * 根据关键字查询项目要件
     * @param draw  绘制次数
     * @param start  查询起始位置
     * @param length    查询条数
     * @param search     关键字
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @GetMapping("/requirements/list")
    @ApiOperation(value = "根据关键字查询项目要件",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "draw",value = "绘制次数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "start",value = "查询起始位置", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "length",value = "查询条数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "search",value = "关键字", required = true, dataType = "String", paramType = "String", dataTypeClass = String.class),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ReturnResult> requirementsQueryWordMethod(Integer draw,
                                                                     Integer start,
                                                                     Integer length,
                                                                     String search,
                                                                     @ApiIgnore HttpSession session){

        // 参数校验
        if (!EmptyUtils.isIntegerEmpty(start) && !EmptyUtils.isIntegerEmpty(length)) {
            return ReturnOperator.createResultMsg(draw, 0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
        List<ProjectImportantDocumentVo> projectImportantDocumentVos = null;
        Integer totalCount = 0;
        if (role_id != 1) {
            //不是管理员情况下

            // 关键字参数校验
            if (EmptyUtils.isStringEmpty(search)) {
                // 查询总记录数
                totalCount = projectImportantDocumentService.queryAllByWordAndUserId(search,user_id).size();
                // 分页查询项目要件列表
                projectImportantDocumentVos = projectImportantDocumentService.queryAllByWordAndUserIdLimit(search, start, length, user_id);
            } else {
                // 查询总记录数
                totalCount = projectImportantDocumentService.queryAllByUserId(user_id).size();
                // 分页查询项目要件列表
                projectImportantDocumentVos = projectImportantDocumentService.queryAllByUserIdLimit(start, length, user_id);
            }

        } else {
            //是管理员情况下
            // 关键字判断是否为空
            if (EmptyUtils.isStringEmpty(search)) {
                // 查询总记录数
                totalCount = projectImportantDocumentService.queryAllByWord(search).size();
                // 分页查询项目要件列表
                projectImportantDocumentVos = projectImportantDocumentService.queryAllByWordLimit(search, start, length);
            } else {
                // 查询总记录数
                totalCount = projectImportantDocumentService.queryAll().size();
                // 分页查询项目要件列表
                projectImportantDocumentVos = projectImportantDocumentService.queryAllByLimit(start, length);
            }

        }

        // 查询结果判断是否为空
        if (!EmptyUtils.isProjectImportantDocumentListEmpty(projectImportantDocumentVos)) {
            return ReturnOperator.createResultMsg(draw, 0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(draw, totalCount, totalCount,
                projectImportantDocumentVos,  HttpStatus.OK);
    }

    /**
     * 添加项目要件
     * @param projectImportantDocument  项目要件对象
     * @param errors    错误信息存储对象
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @PostMapping(value = "/requirements")
    @ApiOperation(value = "添加项目要件",produces = "application/json",consumes = "application/x-www-form-urlencoded")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> requirementsAddMethod(@Valid @RequestBody ProjectImportantDocumentVo projectImportantDocument,
                                                           @ApiIgnore Errors errors, @ApiIgnore HttpSession session){

        // 对象参数校验
        if (errors.hasErrors()) {
            List<ObjectError> oes = errors.getAllErrors();
            for (ObjectError oe : oes) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    return ReturnOperator.createResultMsg("", fe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                } else {
                    return ReturnOperator.createResultMsg("", oe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                }
            }
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 如果当前登录的不是管理员用户(企业用户)
        if (role_id != 1) {
            // 获取当前登录的企业用户id 关联到企业 本关联只用来限制企业用户只查看自己
            Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
            projectImportantDocument.setEnUserId(user_id);
        }

        // true变成 有  false 变成无
        projectImportantDocument.setBusinessLicenseInfo("true".equalsIgnoreCase(projectImportantDocument.getBusinessLicenseInfo())?"有":"无");
        projectImportantDocument.setIsFeasibilityResearchReport("true".equalsIgnoreCase(projectImportantDocument.getIsFeasibilityResearchReport())?"有":"无");
        projectImportantDocument.setIsFeasibilityReviewComments("true".equalsIgnoreCase(projectImportantDocument.getIsFeasibilityReviewComments())?"有":"无");
        projectImportantDocument.setIsEnergyConservationReport("true".equalsIgnoreCase(projectImportantDocument.getIsEnergyConservationReport())?"有":"无");

        // 项目要件添加数据库
        ProjectImportantDocument projectImportantDocument_new = projectImportantDocumentService.insert(projectImportantDocument);

        // 对插入后的数据检查
        if (!EmptyUtils.isProjectImportantDocumentEmpty(projectImportantDocument_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_INSERT_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_INSERT_SUCCESS,"", ServerStatus.OK,
                new ArrayList(), projectImportantDocument_new, HttpStatus.OK);
    }

    /**
     * 修改项目要件
     * @param projectImportantDocument  项目要件对象
     * @param errors    错误信息存储对象
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @PutMapping("/requirements")
    @ApiOperation(value = "修改项目要件",produces = "application/json",consumes = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> requirementsChangeByIdMethod(@Valid @RequestBody ProjectImportantDocumentVo projectImportantDocument,
                                                                  @ApiIgnore Errors errors, @ApiIgnore HttpSession session){

        // 对象参数校验
        if (errors.hasErrors()) {
            List<ObjectError> oes = errors.getAllErrors();
            for (ObjectError oe : oes) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    return ReturnOperator.createResultMsg("", fe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                } else {
                    return ReturnOperator.createResultMsg("", oe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                }
            }
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 如果当前登录的不是管理员用户(企业用户)
        if (role_id != 1) {
            // 获取当前登录的企业用户id 关联到企业 本关联只用来限制企业用户只查看自己
            Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));
            projectImportantDocument.setEnUserId(user_id);
        }

        // true变成 有  false 变成无
        projectImportantDocument.setBusinessLicenseInfo("true".equalsIgnoreCase(projectImportantDocument.getBusinessLicenseInfo())?"有":"无");
        projectImportantDocument.setIsFeasibilityResearchReport("true".equalsIgnoreCase(projectImportantDocument.getIsFeasibilityResearchReport())?"有":"无");
        projectImportantDocument.setIsFeasibilityReviewComments("true".equalsIgnoreCase(projectImportantDocument.getIsFeasibilityReviewComments())?"有":"无");
        projectImportantDocument.setIsEnergyConservationReport("true".equalsIgnoreCase(projectImportantDocument.getIsEnergyConservationReport())?"有":"无");

        // 更新项目要件数据库
        ProjectImportantDocument projectImportantDocument_new = projectImportantDocumentService.update(projectImportantDocument);
        // 更新后的数据检查
        if (!EmptyUtils.isProjectImportantDocumentEmpty(projectImportantDocument_new)) {
            return ReturnOperator.createResultMsg("",ServerStatus.DATA_UPDATE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_UPDATE_SUCCESS,"", ServerStatus.OK,
                new ArrayList(), projectImportantDocument_new, HttpStatus.OK);
    }


    /**
     * 根据id 删除项目要件
     * @param id    项目要件id
     * @return
     */
    @DeleteMapping("/requirements/{id}")
    @ApiOperation(value = "根据id 删除项目要件",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "项目要件id", required = true, dataType = "Long", paramType = "Long", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> requirementsDeleteByIdMethod(@PathVariable("id") Long id, @ApiIgnore HttpSession session){

        // id参数校验
        if (!EmptyUtils.isLongEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // id删除失败结果判断
        if (!projectImportantDocumentService.deleteById(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_DELETE_ERR, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList<>(), new Boolean(true), HttpStatus.OK);
    }

    /**
     * id数组批量删除项目要件
     * @param ids   项目要件id数组
     * @return
     */
    @DeleteMapping("/requirements/list")
    @ApiOperation(value = "id数组批量删除项目要件",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "ids",value = "项目要件id数组", required = true, dataType = "Long", paramType = "Long[]", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> requirementsDeleteListByIDMethod(Long[] ids, @ApiIgnore HttpSession session){

        // id参数校验
        if (!EmptyUtils.isIdsEmpty(ids)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 循环删除
        for (Long id : ids) {
            projectImportantDocumentService.deleteById(id);
        }

        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList<>(), new Boolean(true), HttpStatus.OK);
    }
}
